// browses json data structures
console.log('jsonDiv :-)');


jsonDiv = function (J,id){

	this.parse = function (J,d){
		//d.innerHTML=JSON.stringify(J);
		switch (typeof(J)){
		case 'string':this.parseString(J,d);break;
		case 'number':this.parseNumber(J,d);break;
		case 'object':
			if (Array.isArray(J)){this.parseArray(J,d)}
			else {this.parseObject(J,d)}			
			break;
		}
	}
	
	this.parseString = function (S,d){
		$(d).append($('<span style="color:red">'+S+'</span>'))
	}

	this.parseNumber = function (N,d){
		$(d).append($('<span style="color:blue">'+N+'</span>'));
	}

	this.parseArray = function (A,d){
		$(d).append(this.tableHorizontal(A));
		//console.log('array: '+J);
	}

	this.parseObject = function (O,d){
		for (x in O){
			var y = $('<p style="color:green">'+x+':</p>');
			this.parse(O[x],y);
			$(d).append(y);
		}
		//
		//console.log('object: '+J);
	}
	
	this.tableHorizontal = function (A){
		var tb = document.createElement('table');
		var tbody = document.createElement('tbody');
		tb.appendChild(tbody);
		var tr = document.createElement('tr');
		for (var i=0;i<A.length;i++){
			var td = document.createElement('td');
			if (Array.isArray(A[i])){td.appendChild(this.tableVertical(A[i]))}
			else {this.parse(A[i],td)};
			tr.appendChild(td);			
		}
		tbody.appendChild(tr);
		return tb;
	}

	this.tableVertical = function (A){
		var tb = document.createElement('table');
		var tbody = document.createElement('tbody');
		tb.appendChild(tbody);
		for (var i=0;i<A.length;i++){
			var tr = document.createElement('tr');
			var td = document.createElement('td');
			if (Array.isArray(A[i])){td.appendChild(this.tableHorizontal(A[i]))}
			else {this.parse(A[i],td)};
			tr.appendChild(td);
			tbody.appendChild(tr);
		}
		return tb;
	}


	if (id){this.div=document.getElementById(id)}
	else {
		this.div=document.createElement('div');
		this.div.id=Math.random().toString().split('.')[1];
		document.body.appendChild(this.div);
		}
	var d = this.div; // to save on typing
	this.parse(J,d);
	return d;
}
